package controllers;

import java.util.Map;

import models.Role;
import models.User;
import spark.ModelAndView;
import spark.Request;
import spark.Response;

public abstract class BaseController {
	protected Request request;
	protected Response response;
	protected String rootPath;
	protected String currentPath;
	
	public BaseController(Request request, Response response) {
		this.request = request;
		this.response = response;
		this.rootPath = request.contextPath();
		this.currentPath = this.rootPath + request.servletPath();
	}
	
	protected User getCredentials() {
		return request.session().attribute("user");
	}
	
	protected boolean isUserInRole(String roleName) {
		User user = (User)request.session().attribute("user");
		return user.getIsUserInRole(roleName);
	}
	
	protected void redirect(String link) {
		if(link.charAt(0) != '/')
			response.redirect(rootPath + "/" + link);
		else response.redirect(rootPath + link);
	}
	
	protected String getCurrentRequestUrl(){
		return request.servletPath();
	}
	
	protected Object render(Map<String, Object> attributes, String view){
		attributes.put("credentials", request.session().attribute("user"));
		attributes.put("rootPath", rootPath);
		attributes.put("currentPath", currentPath);
		attributes.put("content", view);
		return new ModelAndView(attributes, "layout.html");
	}
}